package com.baomidou.springboot.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author TangCaiCai
 * @date 2021/7/29 10:11
 */
@Slf4j
public class MD5Util {
    /**
     * MD5方法
     *
     * @param text 明文
     * @param key  密钥
     * @return 密文
     * @throws Exception
     */
    public static String md5(String text, String key){
        //加密后的字符串
        String encodeStr = DigestUtils.md5Hex(text + key);
        return encodeStr;
    }

    /**
     * MD5验证方法
     *
     * @param text 明文
     * @param key  密钥
     * @param md5  密文
     * @return true/false
     * @throws Exception
     */
    public static boolean verify(String text, String key, String md5) throws Exception {
        //根据传入的密钥进行验证
        String md5Text = md5(text, key);
        if (md5Text.equalsIgnoreCase(md5)) {
            log.info("MD5验证通过");
            return true;
        }

        return false;
    }

    private static final int SIGN_LENGTH = 31;
    public static String encrypt(String text) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(text.getBytes());
            String sign = new BigInteger(1, md.digest()).toString(16);
            if(sign.length() == SIGN_LENGTH){
                sign = "0" + sign;
            }
            return sign;
        } catch (NoSuchAlgorithmException e) {
        }
        return "";
    }
    public static String encrypt16(String text) {
        String md5 = encrypt(text);
        return md5.substring(8, 24);
    }
}
